package com.line.myprojectservice.service.impl;

import cn.hutool.json.JSONUtil;
import com.line.myprojectservice.Mapper.AnswerMapper;
import com.line.myprojectservice.po.Answer;
import com.line.myprojectservice.service.AnswerService;
import com.line.myprojectservice.utils.RedisUtil;
import com.line.myprojectservice.vo.AnswerVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author ：Line
 * @date ： 2022/4/1 19:14
 * @description :TODO
 */
@Service
@Slf4j
public class AnswerServiceImpl implements AnswerService {


    @Resource
    AnswerMapper answerMapper;

    @Override
    public void addAnswer(Answer answer) {
        // 定义id唯一标识
        answerMapper.addAnswer(answer);
        //新增的时候不放入redis，毕竟这又不是VO
    }

    @Override
    public void deleteAnswer(String id) {

        answerMapper.deleteAnswer(id);

        RedisUtil.delete("Answer" + id);

    }

    @Override
    public Object queryAnswerById(String id) {

        try {
            String redisResult = RedisUtil.getString("Answer" + id);
            if (redisResult != null) {
                //热度+1
                RedisUtil.zIncrementScore("HotAnswer", redisResult, 1);
                return redisResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        Answer answer = answerMapper.queryAnswerById(id);
        System.out.println(answer+"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");

        if (answer == null) {
            return answerMapper.queryAnswerNoOtherById(id);
        } else {
            AnswerVo answerVo = answerMapper.queryAnswerAndOtherById(id);
            if (answerVo != null) {
                try {
                    //缓存到Redis
                    RedisUtil.setStrings("Answer" + id, JSONUtil.toJsonPrettyStr(answerVo));
                } catch (Exception e) {
                    log.info("存入redis异常:" + e.getMessage());
                }
            }
            return answerVo;
        }

    }


}

